var _ajax = $.ajax;
$.ajax = function(opt){
    //签名
    var sign = '3L7bfO3OBjucxpuVK+gO0g=='
    var authToken = $.cookie('authToken')
    var roleCode = $.cookie('roleCode')
    var Authorization = ''
    if (authToken) {
        authToken = decodeURIComponent(authToken)
        authToken = JSON.parse(authToken)
        Authorization = 'Bearer ' + authToken.access_token
      }


    if(opt.headers){
        opt.headers.sign = sign
        opt['X-Requested-With'] = 'XMLHttpRequest'
        clientMark = 'mobile'
        roleCode = roleCode
        Authorization = Authorization
    }else{
        opt.headers = {
            sign:sign,
            'X-Requested-With': 'XMLHttpRequest',
            clientMark: 'mobile',
            roleCode: roleCode,
            Authorization: Authorization
        }
    }
    _ajax(opt)
}



// 移动端登录注册合并接口
function userLogin (params) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: appUrl + "/bdc/api/app/login/loginRegisterResult",
            data: params,
            type: 'GET',
            success: function (res) {
                // res = JSON.parse(res)
                resolve(res)
            },
            error: function(err){
                
                reject(err.responseJSON.error)
            }
        });
    })
}

function getAccessToken () {
    return new Promise((resolve, reject) => {
        var openid = ''
       

        var code = getParams().code
        if (!code) {
            wechatLogin()
            return
        }


        $.ajax({
            url: fytest + "/api/OAuthApi/GetAccessToken?code=" + code,
            success: function (data) {
                var res = JSON.parse(data).Data;
                if (!res.openid) {
                    location.href = location.origin + location.pathname
                    reject()
                    return
                }
                
                openid = res.openid
                unionid = res.unionid
                $.cookie('OpenId', openid, { expires: 100, path: '/', domain: 'xueerqin.net' });
                $.cookie('unionID', unionid, { expires: 100, path: '/', domain: 'xueerqin.net' });
                resolve(res)
            }
        });
    })
}

function userWechatInfoForComponent () {
    return new Promise((resolve, reject) => {
        var params = getParams()
        if (!params.code) {
            wechatLogin()
            return
        }
        if (!params.appid) {
            params.appid = appid
        }
       
        $.ajax({
            url: appUrl + "/common/api/app/weChatServer/userWechatInfoForComponent",
            data: {
                appid: params.appid,
                code: params.code
            },
            dataType: "json",
            success: function (res) {
               
            //    authorizerAppId: "wxf7bce0e19b3f0ed7"
            //    openId: "ouScL6Nr4xUdO1U3aDx1bnL3H0F8"
            //    unionId: "oqM0v1ud3MwVz-_9V1BxSj4wBQn8"
                $.cookie('OpenId', res.openId, { expires: 100, path: '/', domain: 'xueerqin.net' });
                $.cookie('unionID', res.unionId, { expires: 100, path: '/', domain: 'xueerqin.net' });
                resolve(res)
            },
            error: function(err){
                
                wechatLogin()
            }
        });
    })
}

function getUnionID (openid) {
    return new Promise((resolve, reject) => {
        var unionid = $.cookie('unionID')
        if (unionid) {
            resolve(unionid)
            return
        }
        $.ajax({
            url: fytest + "/api/OAuthApi/GetUnionID",
            data: {
                data: JSON.stringify({openid: openid}) 
            },
            success: function (res) {
                res = JSON.parse(res)

                unionid = res.unionid
                $.cookie('unionID', unionid, { expires: 100, path: '/', domain: 'xueerqin.net' });
                resolve(unionid)
            }
        });
    })
}

function getUserInfo ({openid, unionid}){
    return new Promise((resolve, reject) => {
        $.ajax({
            url: appUrl + "/bdc/api/app/users/userInfoByOpenId",
            data: {
                openId:openid, unionId: unionid
            },
            success: function (res) {
              
                resolve(res)
            },
            error: function(err){
                
                reject(err)
            }
        });
    })
}

// 401过期刷新
function refreshToken () {
    return new Promise((resolve, reject) => {
        
        var authToken = $.cookie('authToken')
        if (!authToken) {
            var code = getParams().code
            if (!code) {
                wechatLogin()
                return
            }

            reject()
            return
        }

        var params = {
            refresh_Token: (JSON.parse(decodeURIComponent(authToken))).refresh_token,
            clientId: clientId,
            clientSecret: clientSecret

        }
        $.ajax({
            url: authUrl + "/api/auth/login/refresh-token",
            data: JSON.stringify(params) ,
            type: 'post',
            contentType:'application/json',
            success: function (res) {
                
                let domain = '.xueerqin.net'
                $.cookie('authToken', JSON.stringify(res),{
                    expires: 100,
                    path: '/',
                    domain: domain
                })
                resolve()
            },
            error: function(err){
                
                reject(err.responseJSON.error)
            }
        });
    })
}

//移动端首页跳转验证
function mobileIndexCheck () {
    return new Promise((resolve, reject) => {
        var params = {}
        $.ajax({
            url: appUrl + "/bdc/api/app/login/mobileIndexCheck",
            data: params,
            type: 'POST',
            success: function (res) {
                // res = JSON.parse(res)
                resolve(res)
            },
            error: function(err){
                
            }
        });
    })
}

function getParams() {
    var search = location.search
    search = search.replace('?', '')
    var arr = search.split('&')
    var obj = {}
    for (var item of arr) {
        var list = item.split('=')
        obj[list[0]] = list[1]
    }
  
    return obj
}
function wechatLogin () {

    var params = getParams()
   
    if (!params.appid) {
        params.appid = appid
    }
  
    var url = location.origin + location.pathname
    // location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+url+'&response_type=code&scope='+scope+'&state=123&connect_redirect=1#wechat_redirect'
    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+params.appid+"&redirect_uri="+url+"&response_type=code&scope="+scope+"&state=STATE&component_appid=" + component_appid + "#wechat_redirect"
}

// 移动端登录注册合并接口
function miniProgramLogin (params) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: appUrl + "/bdc/api/app/login/loginH5Result",
        data: params,
        type: 'GET',
        success: function (res) {
          // res = JSON.parse(res)
          resolve(res)
        },
        error: function(err){
          reject(err.responseJSON.error)
        }
      });
    })
  }




